import Vue from 'vue'
import VueRouter from 'vue-router'


Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: () => import(/* webpackChunkName: "login" */ '../views/login.vue')
  }, {
    path: '/',
    name: 'home',
    component: () => import(/* webpackChunkName: "home" */ '../views/home.vue'),
    children: [
      {//嵌套路由
        path: 'users',
        name: 'user',
        component: () => import(/* webpackChunkName: "user" */ '../views/users.vue')
      },
      {
        path: 'roles',
        name: 'role',
        component: () => import(/* webpackChunkName: "role" */ '../views/role.vue')
      },
      {
        path: 'rights',
        name: 'rights',
        component: () => import(/* webpackChunkName: "rights" */ '../views/rights.vue')
      }
    ]
  }
]

const router = new VueRouter({
  routes
})
//全局前置路由守卫
router.beforeEach((to, from, next) => {
  // console.log(to,from);
  if (to.path !== '/login') {//如果是的不是登录页
    if (!localStorage.getItem('userinfo')) {//如果没有用户数据
      next('/login')//那就跳转到登录页
    }
  } else if (to.path === '/login') {//如果是登录页
    if (localStorage.getItem('userinfo')) {//但是有userinfo
      next('/')//那就去主页
    }
  }
  next()
})

export default router
